package edu.uwm.capstone.diasmart.types;

import java.text.DecimalFormat;
import java.text.ParseException;

import edu.uwm.capstone.diasmart.R;
import edu.uwm.capstone.diasmart.database.SubType;

public abstract class BaseType implements EditableEntryType {
	private static final String PATTERN = "##0.0#";
	private DecimalFormat formatter = new DecimalFormat(PATTERN);

	@Override
	public String getEditableValue(EntryContext entryContext,
			double value) {
		return getFormattedValue(entryContext, value).replace(
				this.formatter.getDecimalFormatSymbols().getDecimalSeparator(),
				'.');
	}

	@Override
	public String getFormattedValue(EntryContext entryContext,
			double value) {
		return this.formatter.format(value);
	}

	@Override
	public String getMeasurementUnit(EntryContext entryContext) {
		return entryContext.getContext().getString(R.string.quantity);
	}

	@Override
	public String getMeasurementUnit(EntryContext entryContext,
			SubType subType) {
		if ((subType == null) || (subType.getUnit() == null))
			return getMeasurementUnit(entryContext);
		return subType.getUnit();
	}

	@Override
	public double toActualValue(EntryContext entryContext, long value) {
		return value / 1000.0D;
	}

	@Override
	public long toStoredValue(EntryContext entryContext, double value) {
		return (long) (1000.0D * value);
	}

	@Override
	public double toValue(EntryContext entryContext, String value) {
		try {
			value = value.replace('.', this.formatter
					.getDecimalFormatSymbols().getDecimalSeparator());
			double d = this.formatter.parse(value).doubleValue();
			return d;
		} catch (ParseException localParseException) {
		}
		return Double.parseDouble(value);
	}

	@Override
	public String getKeyboardType() {
		return "preference";
	}

	public String toString() {
		return EntryTypeFactory.getTypeString(getType());
	}
}
